package com.ridanlabs.professorwebsite.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.ridanlabs.professorwebsite.general.Authority;
import com.ridanlabs.professorwebsite.models.UserProfile;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class GeneralController {

    @RequestMapping(value = "/", method= RequestMethod.GET)
    public String landing() {
        return "landing";
    }
    
	@PreAuthorize("hasRole('USER')") //first make sure we're a registered user/ later we'll add admin
	@RequestMapping(value="/home")
	public void home(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	UserProfile user = (UserProfile)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	
    	if( user.getAuthorities().contains(Authority.PROFESSOR) ) 
    		req.getRequestDispatcher("/professor/index").forward(req, res);
    	else
    		req.getRequestDispatcher("/student/index").forward(req, res);
    		
    }

    @RequestMapping(value="login", method=RequestMethod.GET)
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		
		if( userService.getCurrentUser() == null)
			response.sendRedirect(userService.createLoginURL("/home"));
		else
			request.getRequestDispatcher("/home").forward(request, response);
	}

    @RequestMapping(value = "/logout", method= RequestMethod.GET)
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();

        String logoutUrl = UserServiceFactory.getUserService().createLogoutURL("/");

        response.sendRedirect(logoutUrl);
    }
}
